package com.linjiang;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class Response extends AbstractHttpServletReponse {
    private static final int SP = ' ';
    private static final int CR = '\r';
    private static final int LF = '\n';


    @Override
    public int getStatus() {
        return status;
    }

    private int status;
    private String message;
    private Map<String, String> headers = new HashMap<>();

    private  ResponseServletOutputStream servletOutputStream = new ResponseServletOutputStream();

    private  OutputStream socketOutputStream;

    public Response(Request request, OutputStream socketOutputStream) {
        this.request = request;
        this.socketOutputStream = socketOutputStream;
    }

    private Request request;


    @Override
    public void setStatus(int i, String s) {
        this.status = i;
        this.message = s;
    }

    @Override
    public void addHeader(String s, String s1) {
        headers.put(s, s1);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return servletOutputStream;
    }

    //完成响应
    public void complete() throws IOException {
        //发送响应
        sendResponseLine();
        sendResponseHeader();
        sendResponseBody();
    }

    private void sendResponseBody() throws IOException {
        socketOutputStream.write(servletOutputStream.getBytes());
    }

    private void sendResponseHeader() throws IOException {
        if (!headers.containsKey("Content-Length")) {
            addHeader("Content-Length", String.valueOf(servletOutputStream.getPos()));
        }
        if (!headers.containsKey("Content-Type")) {
            addHeader("Content-Type", "text/plain;charset=utf-8");
        }
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            socketOutputStream.write(key.getBytes());
            socketOutputStream.write(":".getBytes());
            socketOutputStream.write(value.getBytes());
            socketOutputStream.write("\r\n".getBytes());
        }
        socketOutputStream.write("\r\n".getBytes());
    }

    private void sendResponseLine() throws IOException {
        socketOutputStream.write(request.getProtocol().getBytes());
        socketOutputStream.write(SP);
        socketOutputStream.write(status);
        socketOutputStream.write(SP);
        socketOutputStream.write(message.getBytes());
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }
}
